package vip.zhenzicheng;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.zhenzicheng.entity.Order;
import vip.zhenzicheng.entity.Product;
import vip.zhenzicheng.mapper.OrderMapper;
import vip.zhenzicheng.mapper.ProductMapper;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author zhenzicheng
 * @DESCRIPTION:
 * @DATE: 2022/04/24 6:03 PM
 */
@Service
public class OrderService {
  @Autowired
  private ProductMapper productMapper;

  @Autowired
  private OrderMapper orderMapper;

  @Transactional
  public void reduceStock(Integer id) {
    // 获取库存
    Product product = productMapper.getProduct(id);
    // 模拟耗时
    sleep(500);

    if (product.getStock() <= 0) {
      throw new RuntimeException("out of stock");
    }
    // 减库存
    int i = productMapper.deductStock(id);
    if (i == 1) {
      Order order = new Order();
      order.setUserId(UUID.randomUUID().toString());
      order.setPid(id);
      orderMapper.insert(order);
    } else {
      throw new RuntimeException("deduct stock fail，retry...");
    }
  }

  public void sleep(long wait) {
    try {
      TimeUnit.MILLISECONDS.sleep(wait);
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    }
  }

}
